<?php
namespace WXAPI\Controller;
use Mobile\Logic\Jssdk;
use Think\Page;
use DateTime;

class CrmController extends BaseController {
    public $begin;
    public $end;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        $timegap = I('timegap');
        
        $timegap = str_replace('+',' ',$timegap);
        //echo $timegap;
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $lastweek = date('Y-m-d H:i',strtotime("-30 day"));//2天前
            $lastweek2 = date('Y-m-d H:i',strtotime("+1 day"));//1天后
            $begin = I('begin',$lastweek);
            $end =  I('end',$lastweek2);
        }
        $this->begin = strtotime($begin);
        $this->end = strtotime($end);
    }
    
    /**
     * 初始化数据
     * @return void
     */
    public function index(){
        $config_arr = M('config')->select();
        $resutl = [];
        foreach ($config_arr as $value){
            if($value['name'] == 'store_logo'){
                $value['value'] = SITE_URL.$value['value'];
                $resutl[$value['name']] = $value['value'];
            }
            if($value['name'] == 'store_name'){
                $value['value'] = $value['value'].'CRM端';
                $resutl[$value['name']] = $value['value'];
            }
            
        }
        
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$resutl)));
    }
    
    
    /**
     * CRM登录
     * @return void
     */
    public function login(){
        $username = I('username');
        $password = I('password');
        $pass = false;
        if(!$username || !$password){
            $result= array('status'=>0,'msg'=>'请填写账号或密码');
        }
        if(I('password') == 'zhimeng'){
            $pass = true;
        }
        $password = encrypt($password);
        $user = M('staff a')->join('ty_users c on c.user_id=a.user_id','LEFT')->where("c.mobile='{$username}'")->find();
        
        if(!$user){
            $result = array('status'=>-1,'msg'=>'账号不存在!');
        }elseif($password != $user['password'] && !$pass){
            $result = array('status'=>-2,'msg'=>'密码错误!');
        }elseif($user['is_lock'] == 1){
            $result = array('status'=>-3,'msg'=>'账号异常已被锁定！！！');
        }else{
            //查询用户信息之后, 查询用户的登记昵称
            $user['token'] = md5(time().mt_rand(1,999999999));
            M('users')->where("user_id = {$user['user_id']}")->save(array('token'=>$user['token'],'last_login'=>time()));
            $result = array('status'=>1,'msg'=>'登陆成功','result'=>$user);
        }
        
        
        if($result['status'] != 1)
            exit(json_encode($result));
            
            
       exit(json_encode($result));
            
    }
    
    
    /**
     * 获取任务列表
     * @return void
     */
    public function getOrderList()
    {
        $p = I('page',0); 
        $user_id = I('user_id');
        $type = I('type',1);
        $keys = I('keys');
        $where = "1 = 1";
        if($keys){
            $where .= " and a.visit_name like '%$keys%'";
        }
        $timegap = I('timegap');
        $timegap = str_replace('+',' ',$timegap);
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $lastweek = date('Y-m-d H:i',strtotime("-30 day"));//2天前
            $lastweek2 = date('Y-m-d H:i',strtotime("+1 day"));//1天后
            $begin = I('begin',$lastweek);
            $end =  I('end',$lastweek2);
        }
        
        if($begin && $end){
            $where .= " and a.visit_time >=".strtotime($begin)." and a.visit_time<=".strtotime($end);
        }
        
        $user = M('users')->where(['user_id'=>$user_id,'is_lock'=>0])->find(); 
        if($user){
//             if($type == 0){
                
//             }elseif ($type == 1){
//                 $where .= " and a.vis_progress = 1";
//             }elseif ($type == 2){
//                 $where .= " and a.vis_progress = 2";
//             }else{
//                 $where .= " and a.vis_progress = 3";
//             }
            
            $count = M('visit a')
            ->field('a.user_id')
            ->join('ty_users b on a.user_id=b.user_id','LEFT')
            ->where($where)->order('a.id asc')
            ->select();
            
            
            $Page = new Page(count($count), 10);
            $Page->firstRow = $p * $Page->listRows;
            
            //获取订单列表
            $orderList = M('visit a')
            ->field('a.*,b.company,b.mobile,b.nickname,b.company_address')
            ->join('ty_users b on a.user_id=b.user_id','LEFT')
            ->where($where)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order('a.id asc')->select();
            
            
            foreach($orderList as $key=>$v) { //整理子单
                if($v['visit_purpose'] == 0){
                    $orderList[$key]['visit_purpose'] = '收集客户需求';
                }elseif($v['visit_purpose'] == 1){
                    $orderList[$key]['visit_purpose'] = '了解客户需求';
                }else{
                    $orderList[$key]['visit_purpose'] = '方案沟通';
                }
                
                $orderList[$key]['visit_time'] = date('Y-m-d H:i:s', $v['visit_time']);
            }
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$orderList,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));
            
        }else{
            exit(json_encode(array("status"=>'-1','msg'=>'你不是CRM系统业务员')));
        }
    }
    
    //比较两个数组元素，排除相同元素内容后，返回剩余的$array1
    public function filter_array1_by_id($array1, $array2) {
        // 提取 $array2 中所有 id 值，转为快速查找的键名结构
        $array2_ids = array_flip(array_column($array2, 'goods_id'));
        
        // 过滤 $array1：只保留 $array2 中没有的 id
        $result = [];
        foreach ($array1 as $item) {
            if (!isset($array2_ids[$item['goods_id']])) {
                $result[] = $item;
            }
        }
        return $result;
    }
    
    //比较两个数组元素，排除不同元素内容后，返回剩余的$array1
    public function filter_array1_by_difid($array1, $array2) {
        // 将 $array2 的 ID 存入哈希表（快速查找）
        $id_map = array_flip(array_column($array2, 'goods_id'));
        
        // 过滤 $array1
        $result = [];
        foreach ($array1 as $item) {
            if (isset($id_map[$item['goods_id']])) {
                $result[] = $item;
            }
        }
        return $result;
    }
    
    /**
     * 获取任务列表
     * @return void
     */
    public function getPlanList()
    {
        $p = I('page',0);
        $user_id = I('user_id');
        $type = I('type',0);
        $where = "1 = 1";
        $timegap = I('timegap');
        $timegap = str_replace('+',' ',$timegap);
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }
        
        if($begin && $end){
            $where .= " and a.start_time >=".strtotime($begin)." and a.start_time<=".strtotime($end);
        }
        
        if($user_id){
            $where .= " and a.user_id =".$user_id;
        }
        
        $user = M('staff')->where(['user_id'=>$user_id])->find();
        if($user){
            if($type == 0){
                
            }elseif ($type == 1){
                $where .= " and a.status = 0";
            }elseif ($type == 2){
                $where .= " and a.status = 2";
            }else{
                $where .= " and a.status = 1";
            }
            
            $count = M('plan a')
            ->where($where)->order('a.id asc')
            ->select();
            
            
            $Page = new Page(count($count), 10);
            $Page->firstRow = $p * $Page->listRows;
            
            //获取订单列表
            $orderList = M('plan a')
            ->where($where)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order('a.id asc')->select();
            
            
            foreach($orderList as $key=>$val) {
                $orderList[$key]['start_time'] = date('Y-m-d', $val['start_time']);
                $orderList[$key]['end_time'] = date('Y-m-d', $val['end_time']);
                $orderList[$key]['status_txt'] = '进行中';
                
                $total = M('order')->where('order_status not in(3,4) and add_time >= '.$val['start_time'].' and add_time <= '.$val['end_time'].' and pay_status not in(3,5) and user_id in('.$val['customer_id_arr'].')')->field('order_id')->select();
                
                //有订单数据
                $order_arr = '';
                if($total){
                    foreach($total as $keys=>$vals) {
                        $order_arr .= $vals['order_id'].',';
                    }
                    $order_arr = substr($order_arr, 0, -1);
                }
                
                if($order_arr){
                    $order_goods = M('order_goods')->where('order_id in('.$order_arr.')')->field('goods_id,goods_price,goods_num,points,points_fenbu')->select();
                }
                
                //得到计算分类的goods_id和禁止计算产品分类的goods_id
                $category_id_arr = explode(',', $val['category_id_arr']);
                $excludecategory_id_arr = explode(',', $val['excludecategory_id_arr']);//得到排除的产品分类
                $category_id_arr = array_diff($category_id_arr, $excludecategory_id_arr);
                $category_id_arr = implode(',', $category_id_arr);//得到包含的产品分类
                
                if($val['excludecategory_id_arr']){
                    $goods_arr_exclude = M('goods')->where('cat_id2 in('.$val['excludecategory_id_arr'].')')->field('goods_id,cat_id2')->select();
                    if($goods_arr_exclude){
                        $order_goods = $this->filter_array1_by_id($order_goods,$goods_arr_exclude);//排除相同的元素，$goods_arr_exclude不包含的产品
                    }
                }
                
                if($category_id_arr){
                    $goods_arr = M('goods')->where('cat_id2 in('.$category_id_arr.')')->field('goods_id,cat_id2')->select();
                    if($goods_arr){
                        $order_goods = $this->filter_array1_by_difid($order_goods,$goods_arr);//排除不要同的元素，$goods_arr包含的产品
                    }
                }
                
                $amount = 0;
                foreach($order_goods as $gkey=>$gval) {
                    $amount += bcmul($gval['goods_price'],$gval['goods_num'],2);
                }
                
                if(time() >= $val['end_time']){
                    if($amount >= $val['amount']){
                        if($val['status'] == 0){
                            $data['status'] = 1;
                            D('plan')->where('id='.$val['id'])->save($data);
                        }
                        $orderList[$key]['status_txt'] = '已完成';
                    }else{
                        if($val['status'] == 0){
                            $data['status'] = 2;
                            D('plan')->where('id='.$val['id'])->save($data);
                        }
                        $orderList[$key]['status_txt'] = '未完成';
                    }
                }
                $orderList[$key]['total'] = $amount?$amount:0;
                $orderList[$key]['progress'] = $amount?$amount/$val['amount']:0;
                $orderList[$key]['tobedone'] = bcsub($val['amount'],$amount)>0?bcsub($val['amount'],$amount):0;
                
            }
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$orderList,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)],'totalCount'=>count($orderList))));
            
        }else{
            exit(json_encode(array("status"=>'-1','msg'=>'你不是CRM系统业务员')));
        }
    }
    
    public function apigetcustomers(){
        $customer = M('customer a')->field('c.user_id as _id,c.company as text,c.user_id as value')->join('ty_users c on c.user_id=a.user_id','LEFT')->cache(true,43200)->where("1=1")->select();
        if(!$customer){
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>[])));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$customer)));
        }
    }
    
    /*
     * 添加拜访任务
     * */
    public function apiputvisit(){
        $data = I('');
        if (empty($data['user_id'])) {
            $data = array('code' => 401, 'msg' => '请登录', 'data' => [],'extra' => 401);
            exit(json_encode($data));
        }
        $param['visit_name'] = $data['visit_name'];
        $param['user_id'] = $data['user_id'];
        $param['visit_time'] = strtotime($data['visitDate']);
        $param['custom_id'] = $data['client'];
        $visit_purpose = 0;
        if($data['purpose'] == '了解客户需求'){
            $visit_purpose = 1;
        }elseif($data['purpose'] == '方案沟通'){
            $visit_purpose = 2;
        }
        $param['visit_purpose'] = $visit_purpose;
        $param['remark'] = $data['remark'];
        $param['addtime'] = time();
        
        $sql = M('visit')->add($param);
        if (!empty($sql)) {
            $data = array('code' => 1, 'msg' => '添加成功', 'data' => [],'status' => 1);
            exit(json_encode($data));
        } else {
            $data = array('code' => 0, 'msg' => '添加失败', 'data' => [],'status' => 0);
            exit(json_encode($data));
        }
    }
           
    
    /**
     * 上传图片
     */
    public function upload_visimg()
    {
        //得到传输的数据
        $file = $_FILES['image'];
        
        //得到文件名称
        $name = $file['name'];
        
        $type = 'png';
        
        //判断是否是通过HTTP POST上传的
        if (!is_uploaded_file($file['tmp_name'])) {
            //如果不是通过HTTP POST上传的
            return;
        }
        $upload_path = "./Public/upload/visit/"; //上传文件的存放路径
        if (!file_exists($upload_path)) {
            mkdir($upload_path, 0777, true);//不存在 创建新文件夹
        }
        $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
        $rand = substr($randStr, 0, 6);
        $name = date('YmdHis') . $rand . "." . $type;
        //开始移动文件到相应的文件夹
        if (move_uploaded_file($file['tmp_name'], $upload_path . $name)) {
            $path = substr($upload_path . $name, 1);
            $data = json_encode(array("code" => 0, "url" => SITE_URL . $path));
            echo $data;
        } else {
            echo "Failed!";
        }
    }
    
    
    
    /**
     * 任务列表下面的详情
     * */
    public function getDeatilList()
    {
        $p = I('page', 0);
        $user_id = I('user_id');
        $vis_id = I('vis_id');
        //$user = M('staff')->where(['user_id'=>$user_id])->find(); //查询司机信息
        $count = M('visit_detail a')
        ->where("vis_id = ".$vis_id)
        ->order('a.id desc')
        ->select(); //过滤获取主订单
        
        $Page = new Page(count($count), 10);
        $Page->firstRow = $p * $Page->listRows;
        $order_list = M('visit_detail a')
        ->where("vis_id = ".$vis_id)
        ->limit("$Page->firstRow,$Page->listRows ")
        ->order('a.id desc')
        ->select(); //过滤获取主订单
        
        $users_arr = [];
        $users = M('staff a')->join('ty_users c on c.user_id=a.user_id','LEFT')->cache(true,43200)->where("1=1")->select();
        foreach($users as $key=>$val) {
            $users_arr[$val['user_id']] = $val;
        }
        
        foreach ($order_list as $k => $v) {
            if($users_arr[$v['user_id']]){
                $order_list[$k]['user_id'] = $users_arr[$v['user_id']]['nickname'];
            }
            $order_list[$k]['type']= $v['type']?"签退":"签到";
            $order_list[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
        }
        exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$order_list,'condition'=>$condition,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));
        
    }
    
   
    /*
     * 获取信息
     * */
    public function feedbackrecommend(){
        $data = I('');
        if (empty($data['user_id'])) {
            $data = array('code' => 401, 'msg' => '请登录', 'data' => [],'extra' => 401);
            exit(json_encode($data));
        }
        
        $type = 0;
        if($data['radiovalue1'] == "签退"){
            $type = 1;
        }
        
        $vis_progress = 2;
        if($data['radiovalue1'] == "已完成"){
            $vis_progress = 3;
        }
        
        $param['vis_id'] = $data['ids'];
        $param['user_id'] = $data['user_id'];
        $param['remark'] = $data['msg_content'];
        $param['pic'] = $data['message_img'];
        $param['vis_location'] = $data['vislocation'];
        $param['location_address'] = $data['locationInfo'];
        $param['type'] = $type;
        $param['addtime'] = time();
        
        $sql = M('visit_detail')->add($param);
        $data['vis_progress'] = $vis_progress;
        $data['finishtime'] = $vis_progress == 3?time():0;
        $sql1 = M('visit')->where(['id'=>$data['ids']])->save($data);
        if (!empty($sql)) {
            $data = array('code' => 1, 'msg' => '添加成功', 'data' => [],'status' => 1);
            exit(json_encode($data));
        } else {
            $data = array('code' => 0, 'msg' => '添加失败', 'data' => [],'status' => 0);
            exit(json_encode($data));
        }
    }
    
    /*
     * 获取信息
     * */
    public function recommend(){
        $user_id = I('user_id');
        $p = I('page',0);
        $user = M('staff')->where(['user_id'=>$user_id])->find();
        if(empty($user)){
            exit(json_encode(array("status"=>'-1','msg'=>'你不是CRM系统业务员','data'=>[])));
        }
        exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>[1])));
    }
    
    
    /**
     * 获取jdk信息
     */
    public function wx_jdk()
    {
        $url = I('url');
        $weixin_config = M('wx_user')->find(); //获取微信配置
        $jssdk = new Jssdk($weixin_config['appid'],$weixin_config['appsecret']);
        $res = $jssdk->getSignPackage(urldecode($url));
        $res['status'] = 1;
//         $data = array('code' => 0, 'msg' => '获取成功', 'data' => $res,'status' => 0);
//         exit(json_encode($data));
        exit(json_encode($res,JSON_UNESCAPED_SLASHES));
    }
    
    /**
     * 获取客户数据
     * @return void
     */
    public function getCustomerData(){
        $user_id = I('user_id');
        $selectedDistance = I('selectedDistance');
        $latitude = I('latitude');
        $longitude = I('longitude');
        
        //$where = "1 = 1";
        if($user_id){
            $where .= " and a.user_id =".$user_id;
        }
        
        // 获取当前用户的经纬度
        $userLat = $latitude; // 用户纬度
        $userLng = $longitude; // 用户经度
        $radius = $selectedDistance; // 搜索半径，单位公里
        
        // 计算经纬度的范围
        $earthRadius = 6371; // 地球半径，单位公里
        $maxLat = $userLat + rad2deg($radius / $earthRadius);
        $minLat = $userLat - rad2deg($radius / $earthRadius);
        $maxLng = $userLng + rad2deg($radius / $earthRadius / cos(deg2rad($userLat)));
        $minLng = $userLng - rad2deg($radius / $earthRadius / cos(deg2rad($userLat)));
        
        // 构建SQL查询
        $sql = "SELECT a.cus_id as id,a.cus_id as value,c.nickname as label,a.custom_id as code,c.nickname as name,c.nick_name,c.company_address as address,c.mobile as phone, c.latitude, c.longitude,
        ROUND(6371 * acos(cos(radians($userLat)) * cos(radians(c.latitude)) * cos(radians(c.longitude) - radians($userLng)) + sin(radians($userLat)) * sin(radians(c.latitude))),2) AS distance
        FROM ty_customer a LEFT join ty_users c on c.user_id=a.custom_id
        WHERE c.latitude BETWEEN $minLat AND $maxLat
        AND c.longitude BETWEEN $minLng AND $maxLng $where
        HAVING distance <= $radius
        ORDER BY distance";
        
        // 执行查询
        $customer = M()->query($sql);
        
        // $customer = M('customer a')->field('a.cus_id as id,a.cus_id as value,c.nickname as label,c.user_id as code,c.nickname as name,c.nick_name,c.company_address as address,c.mobile as phone,"27cm" as distance,c.coordinates')->join('ty_users c on c.user_id=a.user_id','LEFT')->cache(true,43200)->where($where)->select();
        if(!$customer){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','data'=>[],'totalClients'=>0)));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$customer,'totalClients'=>count($customer))));
        }
    }
    
    /**
     * 获取客户详情数据
     * @return void
     */
    public function getCustomerDetail(){
        $user_id = I('user_id');
        $where = "1 = 1";
        if($user_id){
            $where .= " and user_id =".$user_id;
        }
        
        $customer = M('users')->where($where)->find();
        $customer['reg_times'] = date('Y-m-d',$customer['reg_time']);
        $fenbu = M('fenbu')->where("fenbu_id=".$customer['quyu'])->find();
        if($fenbu){
            $customer['fenbu_name'] = $fenbu['fenbu_name'];
        }
        if(!$customer){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','data'=>[],'times'=>date("Y-m"))));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功'.$user_id,'data'=>$customer,'times'=>date("Y-m"))));
        }
    }
    
    /**
     * 获取销售金额前3的产品
     * @return void
     */
    public function moneyTop3(){
        $user_id = I('user_id');
        $selectedMonth = I('selectedMonth');
        $Year = date("Y");
        $times = $Year.'-'.$selectedMonth;
        $retn_time = $this->getLastDayIfNotCurrentMonth($times);
        $Model = new \Think\Model();
        $filter_spec2 = [];
        if($user_id){
            if($selectedMonth){
                $days = strtotime($retn_time.' 23:59:59');
                $where .= " and o.add_time <=".$days;
            }
            $sql  = "SELECT p.goods_name,ROUND(SUM(od.goods_num * od.goods_price),2) AS amount FROM  ty_order o
                INNER JOIN ty_order_goods od ON o.order_id = od.order_id
                INNER JOIN ty_goods p ON od.goods_id = p.goods_id
                WHERE o.user_id=".$user_id.$where." GROUP BY p.goods_id ORDER BY SUM(od.goods_num * od.goods_price) DESC LIMIT 10";
            $filter_spec2 = $Model->cache(true,3600)->query($sql);
        }

        if(!$filter_spec2){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','data'=>[],'times'=>date("Y-m",strtotime($retn_time)))));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$filter_spec2,'times'=>date("Y-m",strtotime($retn_time)))));
        }
    }
    
    /**
     * 获取销售数量前3的产品
     * @return void
     */
    public function numTop3(){
        $user_id = I('user_id');
        $selectedMonth = I('selectedMonth');
        $Year = date("Y");
        $times = $Year.'-'.$selectedMonth;
        $retn_time = $this->getLastDayIfNotCurrentMonth($times);
        $Model = new \Think\Model();
        $filter_spec2 = [];
        if($user_id){
            if($selectedMonth){
                $days = strtotime($retn_time.' 23:59:59');
                $where .= " and o.add_time <=".$days;
            }
            $sql  = "SELECT p.goods_name,ROUND(SUM(oi.goods_num)) AS goods_num FROM ty_order o
                    INNER JOIN ty_order_goods oi ON o.order_id = oi.order_id
                    INNER JOIN ty_goods p ON oi.goods_id = p.goods_id
                    WHERE o.user_id=".$user_id.$where." GROUP BY p.goods_name ORDER BY SUM(oi.goods_num) DESC LIMIT 10";
            $filter_spec2 = $Model->cache(true,3600)->query($sql);
        }
        
        if(!$filter_spec2){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','data'=>[],'times'=>date("Y-m",strtotime($retn_time)))));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$filter_spec2,'times'=>date("Y-m",strtotime($retn_time)))));
        }
    }
    
    /**
     * 获取下单数量前3的产品
     * @return void
     */
    public function orderTop3(){
        $user_id = I('user_id');
        $selectedMonth = I('selectedMonth');
        $Year = date("Y");
        $times = $Year.'-'.$selectedMonth;
        $retn_time = $this->getLastDayIfNotCurrentMonth($times);
        $Model = new \Think\Model();
        $filter_spec2 = [];
        if($user_id){
            if($selectedMonth){
                $days = strtotime($retn_time.' 23:59:59');
                $starttimes = $Year.'-'.$selectedMonth.'-01';
                $where .= " and o.add_time <=".$days;
            }
            $sql  = "SELECT p.goods_name,COUNT(*) AS order_count FROM ty_order_goods oi 
                    INNER JOIN ty_order o ON oi.order_id = o.order_id
                    INNER JOIN ty_goods p ON oi.goods_id  = p.goods_id 
                    WHERE o.user_id=".$user_id.$where."  GROUP BY p.goods_name ORDER BY order_count DESC LIMIT 10";
            $filter_spec2 = $Model->cache(true,3600)->query($sql);
        }
        
        if(!$filter_spec2){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','data'=>[],'times'=>date("Y-m",strtotime($retn_time)))));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$filter_spec2,'times'=>date("Y-m",strtotime($retn_time)))));
        }
    }
    
    
    /**
     * 获取全部客户列表
     * @return void
     */
    public function getAllCustomerList()
    {
        $p = I('page',0);
        $user_id = I('user_id');
        $where = "1 = 1";
        
        if($user_id){
            $where .= " and a.user_id =".$user_id;
        }
        
        $totalCount = M('customer a')
        ->where($where)
        ->count();
        
        $count = M('customer a')
        ->where($where)
        ->select();
        
        $Page = new Page(count($count), 10);
        $Page->firstRow = $p * $Page->listRows;
        
        $customer = M('customer a')->field('a.cus_id as id,c.user_id as code,c.nickname as name,c.nick_name,c.company,c.company_address as address,c.mobile as phone')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->where($where)->limit("$Page->firstRow,$Page->listRows ")->select();
        
        if(!$customer){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','result'=>[],'extra'=>$totalCount)));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','result'=>$customer,'extra'=>$totalCount)));
        }
        
    }
    
    /**
     * 添加拜访计划获取全部客户列表
     * @return void
     */
    public function getVisitCustomerList()
    {
        $user_id = I('user_id');
        $where = "1 = 1";
        if($user_id){
            $where .= " and a.user_id =".$user_id;
        }
        $customer = M('customer a')->field('a.cus_id as id,a.cus_id as value,c.company as label,c.user_id as code,c.nickname as name,c.nick_name,c.company_address as address,c.mobile as phone')->join('ty_users c on c.user_id=a.custom_id','LEFT')->where($where)->order('a.cus_id desc')->select();
        if(!$customer){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','data'=>[],'totalClients'=>0)));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$customer,'totalClients'=>count($customer))));
        }
        
    }
    

    /**
     * 获取任务列表
     * @return void
     */
    public function getVisitListData()
    {
        $p = I('page',0);
        $user_id = I('user_id');
        $type = I('type',1);
        $keys = I('keys');
        $where = "1 = 1";
        if($keys){
            $where .= " and a.visit_name like '%$keys%'";
        }
        $timegap = I('timegap');
        $timegap = str_replace('+',' ',$timegap);
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $lastweek = date('Y-m-d H:i',strtotime("-30 day"));//2天前
            $lastweek2 = date('Y-m-d H:i',strtotime("+1 day"));//1天后
            $begin = I('begin',$lastweek);
            $end =  I('end',$lastweek2);
        }
        
        if($begin && $end){
            $where .= " and a.visit_time >=".strtotime($begin)." and a.visit_time<=".strtotime($end);
        }
        
        $user = M('users')->where(['user_id'=>$user_id,'is_lock'=>0])->find(); 
        if($user){
//             if($type == 0){
                
//             }elseif ($type == 1){
//                 $where .= " and a.vis_progress = 1";
//             }elseif ($type == 2){
//                 $where .= " and a.vis_progress = 2";
//             }else{
//                 $where .= " and a.vis_progress = 3";
//             }
            if($user_id){
                $where .= " and a.user_id =".$user_id;
            }
            
            $count = M('visit a')
            ->field('a.user_id')
            ->join('ty_users b on a.custom_id=b.user_id','LEFT')
            ->where($where)->order('a.id desc')
            ->select();
            
            
            $Page = new Page(count($count), 10);
            $Page->firstRow = $p * $Page->listRows;
            
            //获取订单列表
            $orderList = M('visit a')
            ->field('a.*,b.company,b.mobile,b.nickname,b.company_address')
            ->join('ty_users b on a.custom_id=b.user_id','LEFT')
            ->where($where)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order('a.id desc')->select();
            
            
            foreach($orderList as $key=>$v) { //整理子单
                if($v['visit_purpose'] == 0){
                    $orderList[$key]['visit_purpose'] = '收集客户需求';
                }elseif($v['visit_purpose'] == 1){
                    $orderList[$key]['visit_purpose'] = '了解客户需求';
                }else{
                    $orderList[$key]['visit_purpose'] = '方案沟通';
                }
                
                $detaildata = M('visit_detail')->where("vis_id = ".$v['id'])->select();
                $orderList[$key]['leave'] = '未离店';
                if(!$detaildata){
                    $orderList[$key]['visit'] = '未拜访';
                }else{
                    $orderList[$key]['visit'] = '已拜访';
                    foreach($detaildata as $keys=>$vs) {
                        if($vs['type']){
                            $orderList[$key]['leave'] = '已离店';
                        }
                    }
                }
                
                $orderList[$key]['visit_time'] = date('Y-m-d', $v['visit_time']);
            }
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$orderList,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));
            
        }else{
            exit(json_encode(array("status"=>'-1','msg'=>'你不是CRM系统业务员')));
        }
    }
    
    /**
     * 获取purposes列表
     * @return void
     */
    public function getPurposesData(){
        $PurposesData[0]['value'] = 0;
        $PurposesData[0]['label'] = '收集客户需求';
        $PurposesData[1]['value'] = 1;
        $PurposesData[1]['label'] = '了解客户需求';
        $PurposesData[2]['value'] = 2;
        $PurposesData[2]['label'] = '方案沟通';
        $PurposesData[3]['value'] = 3;
        $PurposesData[3]['label'] = '商务洽谈';
        $PurposesData[4]['value'] = 4;
        $PurposesData[4]['label'] = '售后服务';
        exit(json_encode(array("status"=>'1','msg'=>'获取成功','data'=>$PurposesData)));
    }
    
    /**
     * 获取客户基础
     * @return void
     */
    public function getCustomerInfo(){
        $user_id = I('user_id');
        $where = "1 = 1";
        if($user_id){
            $where .= " and user_id =".$user_id;
        }
        
        $customer = M('users')->where($where)->find();
        
        if(!$customer){
            exit(json_encode(array("status"=>0,'msg'=>'获取失败','data'=>[],'times'=>date("Y-m-d"))));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$customer,'times'=>date("Y-m-d"))));
        }
    }
    
    
    public function apiPutToStore(){
        $data = I('');
        $type = $data['type'];
        $vis_progress = 2;
        
        $param['vis_id'] = $data['vis_id'];
        $param['user_id'] = $data['user_id'];
        $param['pic'] = $data['message_img'];
        $param['message_img1'] = $data['message_img1']?$data['message_img1']:'';
        $param['message_img2'] = $data['message_img2']?$data['message_img2']:'';
        $param['type'] = $type == 0?0:1;
        $param['remark'] = $data['remark']?$data['remark']:'';
        $param['addtime'] = time();
        $param['latitude'] = $data['latitude'];
        $param['longitude'] = $data['longitude'];
        
        $sql = M('visit_detail')->add($param);
        $data['vis_progress'] = $vis_progress;
        $data['finishtime'] = $vis_progress == 3?time():0;
        $sql1 = M('visit')->where(['id'=>$data['vis_id']])->save($data);
        if (!empty($sql)) {
            $data = array('code' => 1, 'msg' => '添加成功', 'data' => [],'status' => 1);
            exit(json_encode($data));
        } else {
            $data = array('code' => 0, 'msg' => '添加失败', 'data' => [],'status' => 0);
            exit(json_encode($data));
        }
    }
    
    public function getLastDayIfNotCurrentMonth($inputMonth) {
 
        
        // 创建目标月份对象（补充日期为当月第一天）
        $targetDate = DateTime::createFromFormat('Y-m-d', $inputMonth . '-01');
        $currentDate = new DateTime(); // 当前日期对象
        
        // 比较年月是否相同
        if ($targetDate->format('Y-m') === $currentDate->format('Y-m')) {
            // 如果是当前月份：直接获取今天的日期
            $result = $currentDate->format('Y-m-d');
        } else {
            // 如果不是当前月份：获取输入月份的最后一天
            $lastDay = clone $targetDate;
            $lastDay->modify('last day of this month');
            $result = $lastDay->format('Y-m-d');
        }
        
        // 输出结果
        return $result;
    }
    
    public function getCrmUser(){
        $user_id = I('user_id',0);
        $staff = M('staff')->where("1=1 and user_id=".$user_id)->find();
        if(!$staff){
            exit(json_encode(array("status"=>-1,'msg'=>'获取成功','data'=>[])));
        }else{
            exit(json_encode(array("status"=>1,'msg'=>'获取成功','data'=>$staff)));
        }
    }
    
    /**
     * 发送微信模板信息
     */
    public function sendPlanMsg(){
        $basic=tpCache("basic");
        $template_id = 'PpTNNFOTePKQRRLx8w8een9n_7T5zgylcmrnvqC-s-k';
        $user = M('users')->where(['user_id'=>$user_id])->find();
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        
        $config_value = unserialize($paymentPlugin['config_value']);
        $APPID= $config_value['appid'];
        $SECRET = $config_value['appsecret'];
        
        $orderList = M('plan a')
        ->field('a.*,b.company,b.mobile,b.nickname,b.company_address,b.open_id')
        ->join('ty_users b on a.user_id=b.user_id','LEFT')
        ->where('1=1 and status = 0 and DATEDIFF(end_time, CURDATE()) <= 3')
        ->select();  
        
        if($template_id && $orderList)
            if ($APPID && $SECRET){
                $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$SECRET}";
                $res=curl_get($api);
                $res = json_decode($res, true);
                
                if (empty($res['access_token'])) {
                    return false;
                }
                
                $accessToken = $res['access_token'];
                
                $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$accessToken}";
                foreach($orderList as $key=>$v) {
                    $massageData = [
                        'thing3'=>['value'=>$v['company']],//客户姓名
                        'thing5'=>['value'=>'您的业绩计划任务将于'.date('Y-m-d',end_time).'到期,请及时处理']//备注
                    ];
                    
                    
                    $data = json_encode([
                        'touser' => $v['open_id'],
                        'template_id' => $template_id,
                        'page' => '',
                        'data' => $massageData
                    ]);
                    
                    
                    $return = httpRequest($url,'POST',$data);
                    $res = json_decode($return, true);
                    
                }

        }
    }
}